<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" v-for="item in cateList" :key="item.id" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="initArtListFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetListFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" @click="showPubDialogFn" class="btn-pub">发表文章</el-button>
        <!-- 对话框 -->
        <el-dialog title="发表文章" :visible.sync="pubDialogVisible" :before-close="handleClose" fullscreen
          @close="onDialogClosedFn">
          <el-form :model="pubForm" :rules="pubFormRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="文章标题" prop="title">
              <el-input placeholder="请输入标题" v-model="pubForm.title"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id">
              <el-select placeholder="请选择分类" style="width:100%" v-model="pubForm.cate_id">
                <el-option :label="item.cate_name" v-for="item in cateList" :key="item.id" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <quill-editor v-model="pubForm.content"></quill-editor>
            </el-form-item>
            <el-form-item>
              <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref='imgRef'>
            </el-form-item>
            <el-form-item>
              <input type="file" style="display:none" ref="iptFileRef" accept="image/*" @change="onCoverChangeFn">
              <el-button type="text" @click="chooseImgFn">+选择封面</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
              <el-button type="info" @click="pubArticleFn('草稿')">成为草稿</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border>
        <el-table-column prop="title" label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类">
        </el-table-column>
        <el-table-column prop="pub_date" label="发表时间">
          <template v-slot="{ row }">
            <span>{{ $formatDate(row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" @click="deleteArticle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="this.total">
      </el-pagination>
      <!-- 查看文章详情的对话框 -->
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>
        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        <!-- 分割线 -->
        <el-divider></el-divider>
        <!-- 文章的封面 -->
        <img :src="baseURL + artDetail.cover_img" alt="" />
        <!-- 文章的详情 -->
        <div v-html="artDetail.content" class="detail-box"></div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import defaultImg from '@/assets/images/cover.jpg'
import { getArticleListAPI, uploadArticleAPI, getArtCateListAPI, getArticleDetailFn, delArticleAPI } from '@/api'
import { baseURL } from '@/utils/request'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubDialogVisible: false,
      // 表单数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '', // 文章的内容
        cover_img: null,
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      cateList: [], // 文章分类
      artList: [], // 文章的列表数据
      total: 0, // 总数据条数
      detailVisible: false, // 控制文章详情对话框的显示与隐藏
      artDetail: {}, // 文章的详情信息
      baseURL
    }
  },
  created () {
    this.initCateList()
    this.initArtListFn()
  },
  methods: {
    /* 显示对话框 */
    showPubDialogFn () {
      this.pubDialogVisible = true
    },
    /* 对话框关闭的回调(暂停的对话框的关闭) */
    async handleClose (done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return
      // 确认关闭
      done()
    },
    /* 显示选择图片 */
    chooseImgFn () {
      this.$refs.iptFileRef.click()
    },
    /* input的change回调 */
    onCoverChangeFn (e) {
      /* 获取用户选择的文件的列表 */
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      } else {
        /* 用户选择封面 */
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        console.log(url)
        this.$refs.imgRef.setAttribute('src', url)
      }
    },
    /* button回调 */
    pubArticleFn (state) {
      this.pubForm.state = state
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return this.$message.error('请完善文章信息')
        if (!this.pubForm.cover_img) return this.$message.error('请选择文章封面')
        /* 创建FormData对象 */
        const fd = new FormData()
        /* 向fd追加数据 */
        Object.keys(this.pubForm).forEach((key) => { fd.append(key, this.pubForm[key]) })
        const { data: res } = await uploadArticleAPI(fd)
        if (res.code !== 0) return this.$message.error('发布文章失败')
        this.$message.success('发布文章成功')
        this.pubDialogVisible = false
        /* 刷新文章列表数据 */
        this.initArtListFn()
      })
    },
    /* 获取文章分类 */
    async initCateList () {
      const { data: res } = await getArtCateListAPI()
      console.log(res)
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    /* 对话框关闭的回调 */
    onDialogClosedFn () {
      this.$refs.ruleForm.resetFields()
      this.pubForm.content = ''
      this.$refs.imgRef.setAttribute('src', defaultImg)
    },
    /* 初始化文章列表 */
    async initArtListFn () {
      const { data: res } = await getArticleListAPI(this.q)
      if (res.code !== 0) return this.$message.error('获取文章列表失败')
      console.log(res)
      this.artList = res.data
      this.total = res.total
    },
    /* 分页器获取数据量的回调 */
    handleSizeChangeFn (newSize) {
      this.q.pagesize = newSize
      /* 默认展示第一页数据 */
      this.q.pagenum = 1
      this.initArtListFn()
    },
    /* 分页器页数的回调 */
    handleCurrentChangeFn (newPage) {
      this.q.pagenum = newPage
      this.initArtListFn()
    },
    /* 重置按钮的回调函数 */
    resetListFn () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtListFn()
    },
    /* 详情页 */
    async showDetail (id) {
      const { data: res } = await getArticleDetailFn(id)
      if (res.code !== 0) return this.$message.error('获取文章详情失败')
      this.artDetail = res.data
      this.detailVisible = true
    },
    /* 删除文章 */
    // async deleteArticle (id) {
    //   const confirmResult = this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).catch(err => err)
    //   if (confirmResult === 'cancel') return
    //   /* 执行删除操作 */
    //   const { data: res } = await delArticleAPI(id)
    //   if (res.code !== 0) return this.$message.error('删除失败')
    //   this.$message.success('删除成功')
    //   /* 刷新列表数据 */
    //   this.resetListFn()
    // }
    deleteArticle (id) {
      const confirmResult = this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (confirmResult === 'cancel') return
        /* 执行删除操作 */
        const { data: res } = await delArticleAPI(id)
        if (res.code !== 0) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        /* 刷新列表数据 */
        this.resetListFn()
      }).catch(err => err)
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .btn-pub {
    margin-top: 5px;
  }

  ::v-deep .ql-editor {
    min-height: 300px;
  }

  .cover-img {
    width: 400px;
    height: 280px;
    object-fit: cover;
  }

  .el-pagination {
    margin-top: 15px;
  }

  .title {
    font-size: 24px;
    text-align: center;
    font-weight: normal;
    color: #000;
    margin: 0 0 10px 0;
  }

  .info {
    font-size: 12px;

    span {
      margin-right: 20px;
    }
  }

  // 修改 dialog 内部元素的样式，需要添加样式穿透
  ::v-deep .detail-box {
    img {
      width: 500px;
    }
  }
}
</style>
